package cn.quang.search.admin.service.impl;

import cn.quang.search.admin.entity.dto.Operator;

import cn.quang.search.admin.entity.dto.Result;
import cn.quang.search.admin.entity.po.*;
import cn.quang.search.admin.entity.vo.fetcher.SearchResultFetcherRequest;
import cn.quang.search.admin.mapper.*;
import cn.quang.search.admin.service.ISearchResultFetcherService;
import cn.quang.search.admin.service.common.RedisService;
import cn.quang.search.admin.utils.AssertUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:  Entity Generator
 * @since:  2024-02-28 11:00:47
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SearchResultFetcherService implements ISearchResultFetcherService {
	private final SearchResultFetcherMapper searchResultFetcherMapper;
	private final SearchResultFetcherTableRelationMapper searchResultFetcherTableRelationMapper;
	private final SearchResultFetcherFieldDicRelationMapper searchResultFetcherFieldDicRelationMapper;
	private final EntityLogicTableMapper entityLogicTableMapper;
	private final EntityFieldDicMapper entityFieldDicMapper;
	private final SearchSceneMapper searchSceneMapper;
	private final SearchSceneConfigMapper searchSceneConfigMapper;
	private final SearchSceneFetcherConfigMapper searchSceneFetcherConfigMapper;
	
	private final SearchConfigChangeService searchConfigChangeService;
	private final RedisService redisService;

	private static final String LOCK_KEY = "CRM3$SEARCH_FETCHER$";
	private static final int EXPIRE_SECONDS = 60;

	/**
	 * 添加条件解析器
	 * @param operator 操作人
	 * @param request 请求参数
	 */
	@Override
	public Result<Long> add(Operator operator, SearchResultFetcherRequest request){
		Result<Long> aopResult = new Result<>();
		AssertUtils.argumentBlank(request.getDic(), "必须提供取数器标识");
		AssertUtils.argumentBlank(request.getName(), "必须提供取数器名称");
		List<SearchResultFetcherRequest.LogicTableRequest> logicTables = request.getLogicTables();
		AssertUtils.argumentCollectionEmpty(logicTables, "必须提供取数器关联的逻辑表");
		List<SearchResultFetcherRequest.FieldDicRequest> fieldDices = request.getFieldDices();
		if(CollectionUtils.isEmpty(fieldDices)){
			fieldDices = Lists.newArrayList();
		}

		String dic = request.getDic();
		String uniqueKey = LOCK_KEY + dic;
		Result<?> checkResult = checkDicLogicTableRelations(0, request.getDic(), request.getLogicTables());
		if(checkResult.isFail()) {
			return aopResult.changeErr(checkResult.getMessage());
		}

		String requestId = UUID.randomUUID().toString();
		if(redisService.tryLock(uniqueKey, requestId, EXPIRE_SECONDS)){
			try {
				// 新增condition
				SearchResultFetcher resultFetcher = new SearchResultFetcher();
				resultFetcher.setDic(request.getDic());
				resultFetcher.setName(request.getName());
				resultFetcher.setDescription(request.getDescription());
				resultFetcher.setAnalyzerScfServiceUrl(request.getAnalyzerScfServiceUrl());
				resultFetcher.setAnalyzerScfServiceName(request.getAnalyzerScfServiceName());
				resultFetcher.setAsyncBoost(request.isAsyncBoost());
				Date now = new Date();
				resultFetcher.setCreatorId(operator.getOperatorId());
				resultFetcher.setCreateTime(now);
				resultFetcher.setModifierId(operator.getOperatorId());
				resultFetcher.setModifyTime(now);
				long fetcherId = searchResultFetcherMapper.insert(resultFetcher);

				for (SearchResultFetcherRequest.LogicTableRequest logicTable : logicTables) {
					// 执行表关系添加
					SearchResultFetcherTableRelation relation = new SearchResultFetcherTableRelation();
					relation.setLogicTableId(logicTable.getLogicTableId());
					relation.setFetcherId(fetcherId);
					relation.setCreatorId(operator.getOperatorId());
					relation.setCreateTime(now);
					relation.setModifierId(operator.getOperatorId());
					relation.setModifyTime(now);
					searchResultFetcherTableRelationMapper.insert(relation);
				}

				for (SearchResultFetcherRequest.FieldDicRequest fieldDic : fieldDices) {
					// 执行表关系添加
					SearchResultFetcherFieldDicRelation relation = new SearchResultFetcherFieldDicRelation();
					relation.setFieldDicId(fieldDic.getFieldDicId());
					relation.setFetcherId(fetcherId);
					relation.setCreatorId(operator.getOperatorId());
					relation.setCreateTime(now);
					relation.setModifierId(operator.getOperatorId());
					relation.setModifyTime(now);
					searchResultFetcherFieldDicRelationMapper.insert(relation);
				}
			} catch (Exception e){
				log.error("添加取数器失败", e);
				return aopResult.changeErr("取数器添加失败，系统异常：" + e.getMessage());
			} finally {
				redisService.releaseLock(uniqueKey, requestId);
			}
		}

		return aopResult;
	}

	/**
	 * 校验系统内是否存在取数器和逻辑表的对应关系
	 * @param dic 取数器Key
	 * @param logicTableRequests 逻辑表IDs
	 */
	private Result<?> checkDicLogicTableRelations(long fetcherId, String dic, List<SearchResultFetcherRequest.LogicTableRequest> logicTableRequests) {
		Result<?> aopResult = new Result<>();
		try {
			for (SearchResultFetcherRequest.LogicTableRequest logicTableRequest : logicTableRequests) {
				// 校验在系统内是否存在
				List<SearchResultFetcher> existSearchResultFetchers = searchResultFetcherMapper.selectByDic(dic);
				if (CollectionUtils.isNotEmpty(existSearchResultFetchers)) {
					List<Long> fetcherIds = existSearchResultFetchers.stream().map(SearchResultFetcher::getId).collect(Collectors.toList());
					List<SearchResultFetcherTableRelation> tableRelations = searchResultFetcherTableRelationMapper.selectByFetcherIds(fetcherIds);
					if (CollectionUtils.isNotEmpty(tableRelations)) {
						for (SearchResultFetcherTableRelation tableRelation : tableRelations) {
							if(tableRelation.getLogicTableId() == logicTableRequest.getLogicTableId() && tableRelation.getFetcherId() != fetcherId) {
								return aopResult.changeErr(String.format("已存在取数器(%s)且已与逻辑表(%s)关联，不能重复添加！", dic, logicTableRequest.getLogicTableName()));
							}
						}
					}
				}
			}
		} catch (Exception e) {
			log.error(String.format("校验取数器是否重复出现异常(dic=%s, conditionId=%s)", dic, fetcherId), e);
			return aopResult.changeErr("无法校验取数器配置是否重复，请稍后重试！");
		}
		return aopResult;
	}

	/**
	 * 更新查询条件
	 * @param operator 操作人
	 * @param fetcherId 取数器ID
	 * @param request 更新请求
	 */
	@Override
	public Result<?> update(Operator operator, long fetcherId, SearchResultFetcherRequest request){
		Result<?> aopResult = new Result<>();

		SearchResultFetcher resultFetcher = searchResultFetcherMapper.selectById(fetcherId);
		AssertUtils.argumentNull(resultFetcher, "系统内不存在该取数器，无法更新");
		List<SearchResultFetcherRequest.LogicTableRequest> logicTables = request.getLogicTables();
		if(CollectionUtils.isEmpty(logicTables)){
			logicTables = Lists.newArrayList();
		}
		Result<?> checkResult = checkDicLogicTableRelations(fetcherId, StringUtils.isBlank(request.getDic()) ? resultFetcher.getDic() : request.getDic(), logicTables);
		if(checkResult.isFail()) {
			return aopResult.changeErr(checkResult.getMessage());
		}
		List<SearchResultFetcherRequest.FieldDicRequest> fieldDices = request.getFieldDices();
		if(CollectionUtils.isEmpty(fieldDices)){
			fieldDices = Lists.newArrayList();
		}

		String key = StringUtils.isNotBlank(request.getDic()) ? request.getDic() : resultFetcher.getDic();
		String uniqueKey = LOCK_KEY + key;
		String requestId = UUID.randomUUID().toString();
		if(redisService.tryLock(uniqueKey, requestId, EXPIRE_SECONDS)){
			try {
				Date now = new Date();
				resultFetcher.setDic(request.getDic());
				resultFetcher.setName(request.getName());
				resultFetcher.setDescription(request.getDescription());
				resultFetcher.setAnalyzerScfServiceUrl(request.getAnalyzerScfServiceUrl());
				resultFetcher.setAnalyzerScfServiceName(request.getAnalyzerScfServiceName());
				resultFetcher.setAsyncBoost(request.isAsyncBoost());
				resultFetcher.setModifierId(operator.getOperatorId());
				resultFetcher.setModifyTime(now);
				searchResultFetcherMapper.updateById(resultFetcher);
				// 同时，更新对应关系
				List<SearchResultFetcherTableRelation> tableRelations = searchResultFetcherTableRelationMapper.selectByFetcherId(fetcherId);
				if(tableRelations == null) { tableRelations = Lists.newArrayList(); }
				Map<Long, SearchResultFetcherTableRelation> fetcherTableRelationMap = tableRelations.stream().collect(Collectors.toMap(SearchResultFetcherTableRelation::getLogicTableId, v -> v));
				Map<Long, SearchResultFetcherRequest.LogicTableRequest> requestFetcherTableRelationMap = logicTables.stream().collect(Collectors.toMap(SearchResultFetcherRequest.LogicTableRequest::getLogicTableId, v -> v));

				// 存储增删改的逻辑表名称，用于输出日志
				List<String> newLogicTableNames = Lists.newArrayList();
				List<String> modifyLogicTableNames = Lists.newArrayList();
				List<String> deleteLogicTableNames = Lists.newArrayList();

				// 执行删除(解除取数器和逻辑表的关联关系，需要校验是否存在某个场景基于该逻辑表关联了该取数器，如果存在，则应该先解除场景下的关联关系)
				List<Long> deleteRelationIds = Lists.newArrayList();
				for (SearchResultFetcherTableRelation relation : tableRelations) {
					long logicTableId = relation.getLogicTableId();
					if(!requestFetcherTableRelationMap.containsKey(logicTableId)){
						EntityLogicTable logicTable = entityLogicTableMapper.selectById(relation.getLogicTableId());
						List<SearchSceneConfig> searchScenes = searchSceneConfigMapper.selectByLogicTableId(logicTableId);
						List<SearchSceneFetcherConfig> searchFetcherConfigs = searchSceneFetcherConfigMapper.selectByFetcherId(fetcherId);
						if(CollectionUtils.isNotEmpty(searchScenes) && CollectionUtils.isNotEmpty(searchFetcherConfigs)) {
							Set<Long> sceneIds = searchFetcherConfigs.stream().map(SearchSceneFetcherConfig::getSceneId).collect(Collectors.toSet());
							for (SearchSceneConfig searchScene : searchScenes) {
								if(sceneIds.contains(searchScene.getSceneId())) {
									SearchScene scene = searchSceneMapper.selectById(searchScene.getSceneId());
									return aopResult.changeErr(String.format("查询场景(%s)基于逻辑表(%s)关联了该取数器，必须先解除场景上的关联后，方可在取数器上解绑该逻辑表", String.format("%s(%s)", scene.getCode(), scene.getName()), logicTable.getName()));
								}
							}
						}
						// 删除
						deleteRelationIds.add(relation.getId());
						deleteLogicTableNames.add(logicTable == null ? "未知" : logicTable.getName());
					}
				}
				for (Long deleteRelationId : deleteRelationIds) { searchResultFetcherTableRelationMapper.deleteById(deleteRelationId); }
				// 比较更新逻辑表关系 ： 存在的更新，不存在的新增，未出现在请求中的删除
				for (SearchResultFetcherRequest.LogicTableRequest logicTableRequest : logicTables) {
					SearchResultFetcherTableRelation relation = fetcherTableRelationMap.get(logicTableRequest.getLogicTableId());
					if(relation != null){
						// 已存在的关联关系，执行更新
						relation.setModifierId(operator.getOperatorId());
						relation.setModifyTime(now);
						searchResultFetcherTableRelationMapper.updateById(relation);
						modifyLogicTableNames.add(logicTableRequest.getLogicTableName());
					} else {
						// 新增
						relation = new SearchResultFetcherTableRelation();
						relation.setFetcherId(fetcherId);
						relation.setLogicTableId(logicTableRequest.getLogicTableId());
						relation.setCreatorId(operator.getOperatorId());
						relation.setCreateTime(now);
						relation.setModifierId(operator.getOperatorId());
						relation.setModifyTime(now);
						searchResultFetcherTableRelationMapper.insert(relation);
						newLogicTableNames.add(logicTableRequest.getLogicTableName());
					}
				}
				log.info(String.format("取数器关联逻辑表：新增表%s，修改表%s，删除表%s", newLogicTableNames, modifyLogicTableNames, deleteLogicTableNames));

				// 存储增删改的通用字典名称，用于输出日志
				List<String> newFieldDicNames = Lists.newArrayList();
				List<String> modifyFieldDicNames = Lists.newArrayList();
				List<String> deleteFieldDicNames = Lists.newArrayList();
				List<SearchResultFetcherFieldDicRelation> fieldDicRelations = searchResultFetcherFieldDicRelationMapper.selectByFetcherId(fetcherId);
				if(fieldDicRelations == null) { fieldDicRelations = Lists.newArrayList(); }
				Map<Long, SearchResultFetcherFieldDicRelation> fetcherFieldDicRelationMap = fieldDicRelations.stream().collect(Collectors.toMap(SearchResultFetcherFieldDicRelation::getFieldDicId, v -> v));
				Map<Long, SearchResultFetcherRequest.FieldDicRequest> requestFetcherFieldDicRelationMap = fieldDices.stream().collect(Collectors.toMap(SearchResultFetcherRequest.FieldDicRequest::getFieldDicId, v -> v));
				// 比较更新通用字典关系 ： 存在的更新，不存在的新增，未出现在请求中的删除
				for (SearchResultFetcherRequest.FieldDicRequest fieldDicRequest : fieldDices) {
					SearchResultFetcherFieldDicRelation relation = fetcherFieldDicRelationMap.get(fieldDicRequest.getFieldDicId());
					if(relation != null){
						// 已存在的关联关系，执行更新
						relation.setModifierId(operator.getOperatorId());
						relation.setModifyTime(now);
						searchResultFetcherFieldDicRelationMapper.updateById(relation);
						modifyFieldDicNames.add(fieldDicRequest.getFieldDicName());
					} else {
						// 新增
						relation = new SearchResultFetcherFieldDicRelation();
						relation.setFetcherId(fetcherId);
						relation.setFieldDicId(fieldDicRequest.getFieldDicId());
						relation.setCreatorId(operator.getOperatorId());
						relation.setCreateTime(now);
						relation.setModifierId(operator.getOperatorId());
						relation.setModifyTime(now);
						searchResultFetcherFieldDicRelationMapper.insert(relation);
						newFieldDicNames.add(fieldDicRequest.getFieldDicName());
					}
				}
				// 执行删除
				for (SearchResultFetcherFieldDicRelation relation : fieldDicRelations) {
					if(!requestFetcherFieldDicRelationMap.containsKey(relation.getFieldDicId())){
						EntityFieldDic fieldDic = entityFieldDicMapper.selectById(relation.getFieldDicId());
						// 删除
						searchResultFetcherFieldDicRelationMapper.deleteById(relation.getId());
						deleteFieldDicNames.add(fieldDic == null ? "未知" : fieldDic.getName());
					}
				}
				log.info(String.format("取数器关联通用字典：新增字典%s，修改字典%s，删除字典%s", newFieldDicNames, modifyFieldDicNames, deleteFieldDicNames));

				searchConfigChangeService.triggerByResultFetcher(fetcherId);
			} catch (Exception e) {
				log.error(String.format("取数器(%s)变更失败", fetcherId), e);
				return aopResult.changeErr("取数器更新失败: " + e.getMessage());
			} finally {
				redisService.releaseLock(uniqueKey, requestId);
			}
		}
		return aopResult;
	}

	/**
	 * 删除查询条件
	 * @param operator 操作人
	 * @param fetcherId 条件ID
	 * @return 删除结果
	 */
	@Override
	public Result<?> delete(Operator operator, long fetcherId){
		Result<?> aopResult = new Result<>();
		try {
			SearchResultFetcher searchResultFetcher = searchResultFetcherMapper.selectById(fetcherId);
			if(searchResultFetcher == null) {
				return aopResult.changeErr("系统内已不存在该取数器");
			}

			List<SearchResultFetcherTableRelation> searchResultFetcherTableRelations = searchResultFetcherTableRelationMapper.selectByFetcherId(fetcherId);
			if(CollectionUtils.isNotEmpty(searchResultFetcherTableRelations)){
				List<Long> logicTableIds = searchResultFetcherTableRelations.stream().map(SearchResultFetcherTableRelation::getLogicTableId).distinct().collect(Collectors.toList());
				List<EntityLogicTable> logicTables = entityLogicTableMapper.selectList(new QueryWrapper<EntityLogicTable>().lambda().in(EntityLogicTable::getId, logicTableIds));
				return aopResult.changeErr("存在关联的逻辑表：" + logicTables.stream().map(EntityLogicTable::getName).collect(Collectors.joining(", ")));
			}

			List<SearchResultFetcherFieldDicRelation> fetcherFieldDicRelations = searchResultFetcherFieldDicRelationMapper.selectByFetcherId(fetcherId);
			if(CollectionUtils.isNotEmpty(fetcherFieldDicRelations)){
				List<Long> fieldDicIds = fetcherFieldDicRelations.stream().map(SearchResultFetcherFieldDicRelation::getFieldDicId).distinct().collect(Collectors.toList());
				List<EntityFieldDic> fieldDices = entityFieldDicMapper.selectList(new QueryWrapper<EntityFieldDic>().lambda().in(EntityFieldDic::getId, fieldDicIds));
				return aopResult.changeErr("存在关联的通用字典：" + fieldDices.stream().map(input -> String.format("%s(%s)", input.getDic(), input.getName())).collect(Collectors.joining(", ")));
			}

			// 检查是否存在查询条件关联的查询场景
			List<SearchSceneFetcherConfig> sceneConfigs = searchSceneFetcherConfigMapper.selectByFetcherId(fetcherId);
			if(CollectionUtils.isNotEmpty(sceneConfigs)){
				List<Long> sceneIds = sceneConfigs.stream().map(SearchSceneFetcherConfig::getSceneId).distinct().collect(Collectors.toList());
				List<SearchScene> scenes = searchSceneMapper.selectList(new QueryWrapper<SearchScene>().lambda().in(SearchScene::getId, sceneIds));
				return aopResult.changeErr("存在关联的查询场景：" + scenes.stream().map(input -> String.format("%s(%s)", input.getCode(), input.getName())).collect(Collectors.joining(", ")));
			}

			searchResultFetcherMapper.deleteById(fetcherId);
		} catch (Exception e) {
			log.error(String.format("删除取数器(%s)出现异常", fetcherId), e);
			return aopResult.changeErr("删除取数器出现系统异常：" + e.getMessage());
		}
		return aopResult;
	}

//	@Override
//	public Result<Pagination<SearchResultFetcherListItemVO>> list4View(Operator operator, SearchResultFetcherQueryRequest request) {
//		Result<Pagination<SearchResultFetcherListItemVO>> aopResult = new Result<>();
//
//		SearchGroup searchGroup = new SearchGroup(SearchLogicType.AND);
//		if(StringUtils.isNotBlank(request.getDic())) {
//			searchGroup.addSearch(SearchResultFetcher.COL_DIC, SearchOperator.Equal, request.getDic());
//		}
//		if(StringUtils.isNotBlank(request.getName())){
//			searchGroup.addSearch(SearchResultFetcher.COL_NAME, SearchOperator.Equal, request.getName());
//		}
//		if(StringUtils.isNotBlank(request.getStartCreateTime())){
//			Date startCreateTime = DateUtil.parse(request.getStartCreateTime(), DateUtil.PATTERN_FULL);
//			searchGroup.addSearch(SearchResultFetcher.COL_CREATE_TIME, SearchOperator.GreaterThanOrEqual, startCreateTime);
//		}
//		if(StringUtils.isNotBlank(request.getEndCreateTime())){
//			Date endCreateTime = DateUtil.parse(request.getEndCreateTime(), DateUtil.PATTERN_FULL);
//			searchGroup.addSearch(SearchResultFetcher.COL_CREATE_TIME, SearchOperator.LessThan, endCreateTime);
//		}
//		try {
//			Pagination<SearchResultFetcher> entitiesPagination = this.searchResultFetcherMapper.findEntitiesPagination(null, searchGroup, request.getPageIndex(), request.getPageSize(), String.format("%s desc", EntityDataSource.COL_CREATE_TIME));
//			Pagination<SearchResultFetcherListItemVO> pagination = new Pagination<>(request.getPageIndex(), request.getPageSize(), entitiesPagination.getTotalCount());
//			if(CollectionUtils.isNotEmpty(entitiesPagination)) {
//				for (SearchResultFetcher fetcher : entitiesPagination) {
//					pagination.add(convertToListItemVo(fetcher));
//				}
//			}
//			return aopResult.changeSucc(pagination);
//		} catch (Exception e) {
//			logger.error("取数器查询失败", e);
//			return aopResult.changeErr("取数器查询失败：" + e.getMessage());
//		}
//	}
//
//	private SearchResultFetcherListItemVO convertToListItemVo(SearchResultFetcher fetcher) {
//		SearchResultFetcherListItemVO vo = new SearchResultFetcherListItemVO();
//		vo.setId(fetcher.getId());
//		vo.setDic(fetcher.getDic());
//		vo.setName(fetcher.getName());
//		vo.setDescription(fetcher.getDescription());
//		vo.setAnalyzerScfServiceName(fetcher.getAnalyzerScfServiceName());
//		vo.setAnalyzerScfServiceUrl(fetcher.getAnalyzerScfServiceUrl());
//		vo.setAsyncBoost(fetcher.getAsyncBoost() == DBConstants.DATA_TRUE ? "是" : "否");
//
//		vo.setCreatorName(BspService.getBspUserNameById(fetcher.getCreatorId()));
//		vo.setCreateTimeFormat(DateUtil.format(fetcher.getCreateTime()));
//		vo.setModifierName(BspService.getBspUserNameById(fetcher.getModifierId()));
//		vo.setModifyTimeFormat(DateUtil.format(fetcher.getModifyTime()));
//		return vo;
//	}

//	@Override
//	public Result<SearchResultFetcherDetailVO> detail4View(Operator operator, long id) {
//		Result<SearchResultFetcherDetailVO> aopResult = new Result<>();
//		try {
//			SearchResultFetcher entity = searchResultFetcherMapper.findEntityById(id);
//			return aopResult.changeSucc(convertToDetailVo(entity));
//		} catch (Exception e) {
//			logger.error(String.format("取数器(%s)查询失败", id), e);
//			return aopResult.changeErr("取数器详情查询失败：" + e.getMessage());
//		}
//	}

	/**
	 * 根据逻辑表ID查询关联的自定义取数器
	 * @param operator 操作人
	 * @param logicTableId 逻辑表
	 */
//	@Override
//	public Result<List<SearchResultFetcherListItemVO>> byLogicTableId4View(Operator operator, long logicTableId) {
//		Result<List<SearchResultFetcherListItemVO>> aopResult = new Result<>();
//		try {
//			List<SearchResultFetcherTableRelation> fetcherTableRelations = searchResultFetcherTableRelationMapper.selectByLogicTableId(logicTableId);
//			List<SearchResultFetcherListItemVO> vos = Lists.newArrayList();
//			if(CollectionUtils.isNotEmpty(fetcherTableRelations)) {
//				List<Long> fetcherIds = fetcherTableRelations.stream().map(SearchResultFetcherTableRelation::getFetcherId).collect(Collectors.toList());
//				List<SearchResultFetcher> entitiesByIds = searchResultFetcherMapper.findEntitiesByIds(fetcherIds);
//				if(CollectionUtils.isNotEmpty(entitiesByIds)) {
//					for (SearchResultFetcher fetcher : entitiesByIds) {
//						vos.add(convertToListItemVo(fetcher));
//					}
//				}
//			}
//
//			return aopResult.changeSucc(vos);
//		} catch (Exception e) {
//			logger.error(String.format("根据逻辑表(%s)查询自定义取数器失败", logicTableId), e);
//			return aopResult.changeErr("根据逻辑表查询关联的自定义取数器失败");
//		}
//
//	}
//
//	private SearchResultFetcherDetailVO convertToDetailVo(SearchResultFetcher entity) {
//		SearchResultFetcherDetailVO vo = new SearchResultFetcherDetailVO();
//		vo.setId(entity.getId());
//		vo.setDic(entity.getDic());
//		vo.setName(entity.getName());
//		vo.setDescription(entity.getDescription());
//		vo.setAnalyzerScfServiceName(entity.getAnalyzerScfServiceName());
//		vo.setAnalyzerScfServiceUrl(entity.getAnalyzerScfServiceUrl());
//		vo.setAsyncBoost(entity.getAsyncBoost() == DBConstants.DATA_TRUE);
//		// 开始读取关联的逻辑
//		try {
//			// 读取关联逻辑表
//			List<SearchResultFetcherTableRelation> tableRelations = searchResultFetcherTableRelationMapper.selectByFetcherId(entity.getId());
//			List<LogicTableVO> lagicTableVos = Lists.newArrayList();
//			vo.setLogicTables(lagicTableVos);
//			List<Long> tableIds = tableRelations.stream().map(SearchResultFetcherTableRelation::getLogicTableId).collect(Collectors.toList());
//			if(CollectionUtils.isNotEmpty(tableIds)) {
//				List<EntityLogicTable> logicTables = entityLogicTableMapper.findEntitiesByIds(tableIds);
//				for (EntityLogicTable entityTable : logicTables) {
//					LogicTableVO logicTableVO = new LogicTableVO();
//					logicTableVO.setLogicTableId(entityTable.getId());
//					logicTableVO.setLogicTableName(entityTable.getName());
//					lagicTableVos.add(logicTableVO);
//				}
//			}
//			// 读取关联通用字典
//			List<SearchResultFetcherFieldDicRelation> fieldDicRelations = searchResultFetcherFieldDicRelationMapper.selectByFetcherId(entity.getId());
//			List<FieldDicVO> fieldDicVos = Lists.newArrayList();
//			vo.setFieldDices(fieldDicVos);
//			List<Long> fieldDicIds = fieldDicRelations.stream().map(SearchResultFetcherFieldDicRelation::getFieldDicId).collect(Collectors.toList());
//			if(CollectionUtils.isNotEmpty(fieldDicIds)) {
//				List<EntityFieldDic> fieldDices = entityFieldDicMapper.findEntitiesByIds(fieldDicIds);
//				for (EntityFieldDic fieldDic : fieldDices) {
//					FieldDicVO fieldDicVO = new FieldDicVO();
//					fieldDicVO.setFieldDicId(fieldDic.getId());
//					fieldDicVO.setFieldDicName(fieldDic.getName());
//					fieldDicVos.add(fieldDicVO);
//				}
//			}
//		} catch (Exception e) {
//			logger.error("逻辑表关联的真实表获取失败", e);
//		}
//		return vo;
//	}
}
